/**
 * Created by aa on 2016/9/5.
 *
 * 此处将api访问剥离出来
 */
var express = require('express');
var crypto = require('crypto');
var fs = require("fs");
var path = require("path");
var HttpOperate = require('../nodeLibrary/HttpOperate');
var getListByparId = require('../nodeLibrary/dataOperate/getListByParId');
var fundNavHisList = require('../nodeLibrary/dataOperate/fundNavHisList');
var httpOperate = new HttpOperate();
//此处linux下的路径是以执行命令的目录为相对路径，故服务器执行node命令时必须进入到bin目录下执行开启操作，否则找不到对应的路径
var MAP_MAIN_DATA = path.resolve('../staticData/china.json');
var MAP_DATA = path.resolve('../staticData/mapData.json');
var uuid = require('node-uuid');
var backEndUrl = require('../nodeConfig/environmentConfig');
var httpOperateForHK = new HttpOperate(backEndUrl.hkBackEndUrl);
var newsContructer=require('../nodeLibrary/newsContructer');

class GetData {
    initGetDataRouter(router) {
        //获取中国地图数据
        router.get('/api/getMapMainData', function (req, res) {
            fs.readFile(MAP_MAIN_DATA, function (err, data) {
                if (err) {
                    console.error(err);
                    process.exit(1);
                }
                res.json(JSON.parse(data));
            });
        });

        //获取基金列表数据
        router.post('/api/fundInfoList', function (req, res) {
            httpOperate.httpPost('/pc/fundCtrl/fundInfoList', req.body, (result)=> {
                var realResult = [];
                var resultContent = result.result;
                for (var i = 0; i < resultContent.length; i++) {
                    var resultItem = [
                        resultContent[i].fundCode,
                        resultContent[i].fundFullName + '+' + resultContent[i].fundCode,
                        resultContent[i].nav,
                        resultContent[i].dayReturn,
                        resultContent[i].oneMonthReturn,
                        resultContent[i].quarterReturn,
                        resultContent[i].oneYearReturn,
                        resultContent[i].thisYearReturn
                    ];
                    realResult.push(resultItem);
                }
                var realResultObj = {
                    'totalPage': Math.ceil(result.size / req.body.pageSize),
                    'page': req.body.curPage,
                    'resultContent': realResult,
                    'status': '200'
                };
                res.json(realResultObj);
            });
        });

        //分页获取净值数据
        router.post('/api/fundnavHisList', function (req, res) {
            httpOperate.httpPost('/fundnavHisList', {
                'curPage': req.body.curPage,
                'pageSize': 10,
                'fundCode': req.body.fundCode
            }, (result)=> {
                //构造前端数据结构
                var fundNavHis = {
                    page: req.body.curPage,
                    totalPage: Math.ceil(result.size / 10),
                    list: fundNavHisList.fundNavHisListDataOperate(result)
                };
                res.json(fundNavHis);
            })
        });

        router.get('/api/getListByParId', function (req, res) {
            httpOperate.httpPost('/pc/productInfoCtrl/getListByPar', {
                'parId': req.query.parId,
                'curPage': 1,
                'pageSize': 999999,
                'userId':req.session.userId?req.session.userId:null
            }, (result)=> {
                res.json(getListByparId.getListByParIdDataOperate(result));
            })
        });

        router.get('/api/getCurrentListByParIdForDetail', function (req, res) {
            httpOperate.httpPost('/pc/productInfoCtrl/getListByPar', {
                'parId': req.query.parId,
                'curPage': req.query.curPage,
                'pageSize': req.query.pageSize,
                'userId':req.session.userId?req.session.userId:null
            }, (result)=> {
                var content = getListByparId.getListByParIdDataOperate(result);
                res.json({
                    size: Math.ceil(result.result[0].size / req.query.pageSize),
                    current: parseInt(req.query.curPage),
                    product: content.products
                })
            })
        });

        router.get('/api/getFundNavSeries', function (req, res) {
            var url = '/tlsGet?path=product/getFundNavSeries&params=fundCode=' + req.query.fundCode + ';period=3m';
            httpOperate.httpGet(url, (result)=> {
                var navSeries = result[0].navSeries;
                var resultContentArray = [];
                for (var i = 0; i < navSeries.length; i++) {
                    var resultContent = {
                        date: navSeries[i].date,
                        //nav为空时为货币基金，返回每个交易日的万份收益
                        nav: navSeries[i].nav != null ? navSeries[i].nav : navSeries[i].unitYield
                    };
                    resultContentArray.push(resultContent);
                }
                res.json(resultContentArray);
            })
        });


        //获取验证码
        router.get('/api/getMsgCode', function (req, res) {
            var url = '/userInfo/getMsgCode?mobile=' + req.query.mobile + '&ifJG=1&channel=3';
            httpOperate.httpGet(url, (result)=> {
                res.json(result);
            });
        });

        //注册
        router.post('/api/registUser', function (req, res) {
            httpOperate.httpPost('/userInfo/registUser', req.body, (result)=> {
                res.json(result);
            });
        });

        //登录
        router.post('/api/login', function (req, res) {
            /*var data=Object.assign(req.body,{verifySource:req.sessionID});*/
            var data = {
                pwd: req.body.pwd,
                loginType: req.body.loginType,
                verifyCode: req.body.verifyCode,
                verifySource: req.sessionID
            };
            httpOperateForHK.httpPost('/api/auth/user/' + req.body.name, data, (result)=> {
                if (result.resultCode == '200') {
                    req.session.userId = result.result.id;
                    req.session.mobile= result.result.name;
                }
                res.json(result);
            });
        });

        //短信验证码登录
        router.post('/api/phoneLogin', function (req, res) {
            /*var data=Object.assign(req.body,{verifySource:req.sessionID});*/
            var data = {
                name:req.body.name,
                msgCode:req.body.msgCode,
                loginType: req.body.loginType,
                mobileType: req.body.mobileType
            };
            httpOperate.httpPost('/userInfo/login', data, (result)=> {
                if (result.resultCode == '200') {
                    req.session.userId = result.result.id;
                    req.session.mobile= result.result.name;
                }
                res.json(result);
            });
        });

        //修改密码
        router.put('/api/changePassWord',(req,res)=>{
            var url=`/api/auth/user/${req.session.mobile}/pwd`;
            var data={
                oldPwd:req.body.oldPwd,
                pwd:req.body.pwd,
                verifySource:req.sessionID,
                verifyCode:req.body.verifyCode
            };
            httpOperateForHK.httpPut(url,data,(result)=>{
                res.json(result);
            });
        });

        //简单登出
        router.post('/api/logout', function (req, res) {
            req.session.userId = '';
            res.json("");
        });

        //通过session检查用户登录状态
        router.get('/api/checkLogin', function (req, res) {
            //如果用户登录则返回用户的手机号码
            var loginResult = req.session.userId ? req.session.mobile : '';
            res.json({userId: loginResult.toString()});
        });

        //获取地图项数据
        router.get('/api/getMapData', function (req, res) {
            var target = decodeURIComponent(req.query.target);
            fs.readFile(MAP_DATA, function (err, data) {
                if (err) {
                    console.error(err);
                    process.exit(1);
                }
                if (JSON.parse(data)[target]) {
                    res.json(JSON.parse(data)[target]);
                }
                else {
                    res.json("暂无数据");
                }
            });
        });


        //获取图片验证码
        router.get('/api/getMsgCodeImg', function (req, res) {
            /*       console.log(req.sessionID);*/
            var url = '/api/captcha/' + req.sessionID;
            httpOperateForHK.httpGet(url, (result)=> {
                result.result = result.result;
                res.json(result);
            });
        });


        //提交建议
        router.post('/api/saveSuggestion', function (req, res) {
            var data = {
                userId: req.session.userId,
                suggestion: req.body.suggestion
            };
            httpOperate.httpPost('/mgr/suggestionCtrl/save', data, (result)=> {
                res.json(result);
            })
        });

        //新闻指定页数数据
        router.get('/api/article/type/NEWS', function (req, res) {
            //此处直接转发前端的请求
            httpOperateForHK.httpGet(req.originalUrl, (result)=> {
                let dynamicsDetail = {page: 1 + parseInt(req.query.curPage), totalPage: 1, content: []};
                if (result.resultCode == '200') {
                    //前端分页器从1开始计数，故curpage需要加1
                    dynamicsDetail = {
                        page: 1 + parseInt(req.query.curPage),
                        totalPage: Math.ceil(result.size / parseInt(req.query.pageSize)),
                        content: []
                    };
                    for (var i = 0; i < result.result.length; i++) {
                        var resultItem = result.result[i];
                        var contentItem = {
                            reHref: '/hkfsDetail?id=' + resultItem.id,
                            leftTitle: resultItem.title,
                            rightTitle: resultItem.ctsStr
                        };
                        dynamicsDetail.content.push(contentItem);
                    }
                }
                res.json(dynamicsDetail);
            });

        });

        //财富报告指定页数数据
        router.get('/api/article/type/WEALTH_REPORT',(req,res)=>{
            httpOperateForHK.httpGet(req.originalUrl, (result)=> {
                if (result.resultCode == '200') {
                    let wealthReport = newsContructer(result,parseInt(req.query.pageSize),parseInt(req.query.curPage)+1);
                    res.json(wealthReport);
                }
            });
        });

        //焦点透视指定页数数据
        router.get('/api/article/type/FOCUS_VIEW',(req,res)=>{
            httpOperateForHK.httpGet(req.originalUrl, (result)=> {
                if (result.resultCode == '200') {
                    let pointItems = newsContructer(result, parseInt(req.query.pageSize),parseInt(req.query.curPage)+1);
                    res.json(pointItems);
                }
            });
        });

        //财富学堂指定页数数据
        router.get('/api/article/type/WEALTH_SCHOOL',(req,res)=>{
            httpOperateForHK.httpGet(req.originalUrl, (result)=> {
                if (result.resultCode == '200') {
                    let wealthClass = {page: parseInt(req.query.curPage)+1, totalPage:  Math.ceil(result.size/parseInt(req.query.pageSize)), content: []};
                    for (var i = 0; i < result.result.length; i++) {
                        var resultItem = result.result[i];
                        var contentItem = {
                            reHref: '/hkfsDetail?id='+resultItem.id,
                            leftTitle: resultItem.title,
                            rightTitle: resultItem.ctsStr
                        };
                        wealthClass.content.push(contentItem);
                    }
                    res.json(wealthClass);
                }
            });
        });

        //获取文章详情
        router.get('/api/articleDetail',(req,res)=>{
            httpOperateForHK.httpGet(`/api/article/${req.query.id}`, (result)=> {
                if (result.resultCode == '200') {
                    var resultContent={
                        title:result.result.title,
                        contentStr:result.result.contentStr,
                        ctsLongStr:result.result.ctsLongStr
                    };
                    res.json(resultContent);
                }
            });
        });

        return router;
    }
}

module.exports = GetData;